<?php

namespace App\Repositories;

use Carbon\Carbon;
use App\Exceptions\BasicException;
use Illuminate\Support\Facades\DB;
use App\Services\Tools\BankToolsService;

class BankCardRepository
{
    /**
     * @Desc:银行卡列表
     * @param $param
     * @return mixed
     * @author: shiquan
     * @Time: 2022/9/28 23:12
     */
    public function list($param)
    {
        $userBank = app('model_user_bank');
        $userData = app('model_user_data');

        $list = app('model_user_bank')->from($userBank->getTable() . " as t1")
            ->select(['t1.*', 't2.nickname', 't2.user_code'])
            ->leftJoin(DB::raw($userData->getTable(). ' as t2'),'t1.user_id','=','t2.user_id')
            ->where(function ($query) use ($param) {
            if (isset($param['user_code'])) {
                $query->where('t2.user_code', $param['user_code']);
            }
            if (isset($param['cardholder']) && $param['cardholder']) {
                $query->where('cardholder', 'like','%'.$param['cardholder'].'%');
            }
            if (isset($param['card_number']) && $param['card_number']) {
                $query->where('card_number', 'like','%'.$param['card_number'].'%');
            }
            if (isset($param['mobile']) && $param['mobile']) {
                $query->where('t1.mobile', 'like','%'.$param['mobile'].'%');
            }
        })->where('t1.bank_type', 3)->where('t1.is_deleted',0)
            ->orderBy('id', 'desc')
            ->paginate($param['page_size'] ?? 1, ['*'], '', $param['page'] ?? 10);
        foreach ($list as &$item) {
            //对联系方式和银行卡号脱敏处理
            $item->card_number = strReplaces($item->card_number, 6,8,'*');
            $item->mobile = strReplaces($item->mobile, 3,4,'*');
            $item->bank_num = strReplaces($item->bank_num, 4,8,'*');
            $item->add_time = date('Y-m-d H:i:s', $item->add_time);
        }
        return $list;
    }



    /**
     * @Desc:新增
     * @param $param
     * @return bool
     * @author: shiquan
     * @Time: 2022/9/28 23:32
     */
    public function create($params)
    {
        $user = app('model_user_data')->where('user_code', $params['user_code'])->first();
        if (empty($user)){
            throw new BasicException(30002);
        }

        $data['user_id'] = $user['user_id'];
        $data['bank_num'] = $params['bank_num'];
        $data['cardholder'] = $params['cardholder'];
        $data['bank_type'] = 3;
        $data['bank_name'] = $params['bank_name'];
        $data['mobile'] = $params['mobile'];
        $data['bank_zhi'] = $params['bank_zhi'];
        $data['card_number'] = $params['card_number'];
        $data['add_time'] = Carbon::now()->timestamp;
        $data['update_time'] = Carbon::now()->timestamp;
        $data['is_deleted'] = 0;
        if (!$this->checkMaxNum($data['user_id'], true)) throw new BasicException(100097);

        //验证下卡号和银行是否一致
        $BankTool = new BankToolsService();
        $BankToolResult = $BankTool->info($params['bank_num']);
        if (!$BankToolResult['validated']){
            throw new BasicException(100099);
        }
        if ($BankToolResult['bankName'] != $params['bank_name']){
            throw new BasicException(100098);
        }

        $res = app('model_user_bank')->insert($data);
        if ($res){
            return $res;
        } else {
            throw new BasicException(0, '添加失败');
        }
    }

    /**
     * @Desc:详情
     * @param $param
     * @return mixed
     * @author: shiquan
     * @Time: 2022/9/28 23:34
     */
    public function info($param)
    {
        $userBank = app('model_user_bank');
        $userData = app('model_user_data');
        $info = app('model_user_bank')->from($userBank->getTable() . " as t1")->select(['t1.*', 't2.user_code', 't2.nickname'])
            ->leftJoin(DB::raw($userData->getTable(). ' as t2'),'t1.user_id','=','t2.user_id')
            ->where('t1.id', $param['id'])
            ->first();
        return $info;
    }

    /**
     * @Desc:更新
     * @param $param
     * @return bool
     * @author: shiquan
     * @Time: 2022/9/28 23:34
     */
    public function update($params)
    {
        $id = $params['id'];
        $user = app('model_user_data')->where('user_code', $params['user_code'])->first();
        if (empty($user)){
            throw new BasicException(30002);
        }
        unset($params['id']);
        $data['user_id'] = $user['user_id'];
        $data['bank_num'] = $params['bank_num'];
        $data['cardholder'] = $params['cardholder'];
        $data['bank_type'] = 3;
        $data['bank_name'] = $params['bank_name'];
        $data['mobile'] = $params['mobile'];
        $data['bank_zhi'] = $params['bank_zhi'];
        $data['card_number'] = $params['card_number'];
        $data['update_time'] = Carbon::now()->timestamp;
        $data['is_deleted'] = 0;
        if (!$this->checkMaxNum($data['user_id'], false)) throw new BasicException(100097);
        //验证下卡号和银行是否一致
        $BankTool = new BankToolsService();
        $BankToolResult = $BankTool->info($params['bank_num']);
        if (!$BankToolResult['validated']){
            throw new BasicException(100099);
        }
        if ($BankToolResult['bankName'] != $params['bank_name']){
            throw new BasicException(100098);
        }
        $res = app('model_user_bank')->where('id', $id)->update($data);
        if ($res){
            return $res;
        } else {
            throw new BasicException(0, '编辑失败');
        }
    }

    /**
     * @Desc:删除
     * @param $param
     * @return bool
     * @author: shiquan
     * @Time: 2022/9/28 23:35
     */
    public function delete($param)
    {
        $res = app('model_user_bank')->whereIn('id', $param['ids'])->update(['is_deleted' => 1]);
        if ($res){
            return $res;
        } else {
            throw new BasicException(0, '删除失败');
        }
    }

    /**
     * @Desc:检查该用户银行卡数量是否超过了上限
     * @param $userId
     * @param $insert
     * @return bool
     * @author: shiquan
     * @Time: 2022/9/30 14:01
     */
    public function checkMaxNum($userId, $insert = true)
    {
        $num = app('model_user')->where('user_id', $userId)->value('bank_acc_num') ?? 1;
        $isUseNum = app('model_user_bank')->where(['user_id'=> $userId, 'is_deleted' => 0, 'bank_type' => 3])->count();
        if (!$insert){
            $isUseNum--;
        }
        if ($num > $isUseNum){
            return true;
        } else {
            return false;
        }
    }
}
